package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;

public class WordCounter {
	private File dir;
	private String[] allFileNames;

	public WordCounter(String path) {
		dir = new File(path);
		allFileNames = dir.list();
		if (allFileNames == null) {
			System.out
					.println("WordCounter: does not exist or is not a directory");
			System.exit(0);
		}
	}

	public void count() throws IOException {
		Map<String, Integer> counts;
		
		File targetDirFile = new File("counted");
		if(targetDirFile.exists()) {
			FileUtils.forceDelete(targetDirFile);
		}
		FileUtils.forceMkdir(targetDirFile);
		
		for(int i = 0; i < allFileNames.length; i++) {
			counts = new HashMap<String, Integer>();
			File file = new File("cleaned/" + allFileNames[i]);
			
			try {
				FileInputStream fstream = new FileInputStream(file);
				DataInputStream in = new DataInputStream(fstream);
				BufferedReader br = new BufferedReader(new InputStreamReader(in));
				String str;
				
				while((str = br.readLine()) != null) {
					if(!counts.containsKey(str)) {
						counts.put(str, 1);
					} else {
						counts.put(str, counts.get(str) + 1);
					}
				}
				
				br.close();
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			File f = new File("counted/" + "counted_" + allFileNames[i]);
			FileWriter fstream = new FileWriter(f);
			BufferedWriter out = new BufferedWriter(fstream);
			
			for (String word : counts.keySet()) {
				out.write(word + " " + (int) counts.get(word));
				out.newLine();
			}
			out.close();
		}	
	}
}
